
package com.jf.cloud.api.order.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.jf.cloud.api.delivery.feign.DeliveryFeignClient;
import com.jf.cloud.api.product.feign.CategoryShopFeignClient;
import com.jf.cloud.common.cache.constant.CacheNames;
import com.jf.cloud.common.cache.constant.OrderCacheNames;
import com.jf.cloud.common.cache.util.CacheManagerUtil;
import com.jf.cloud.common.cache.util.RedisUtil;
import com.jf.cloud.common.constant.Constant;
import com.jf.cloud.common.order.bo.DeliveryModeBO;
import com.jf.cloud.common.order.constant.DeliveryType;
import com.jf.cloud.common.order.constant.OrderType;
import com.jf.cloud.common.order.dto.DvyTypeDTO;
import com.jf.cloud.common.order.vo.*;
import com.jf.cloud.common.product.constant.PreSaleType;
import com.jf.cloud.common.product.constant.SpuMold;
import com.jf.cloud.common.product.constant.SpuType;
import com.jf.cloud.common.product.constant.SupplierDeliveryType;
import com.jf.cloud.common.util.PriceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 确认订单适配
 *
 * @author zz
 * @date 2020/12/07
 */
@Component
public class ConfirmOrderManager {
    private final Logger LOGGER = LoggerFactory.getLogger(ConfirmOrderManager.class);


    @Autowired
    private CacheManagerUtil cacheManagerUtil;

    @Autowired
    private DeliveryFeignClient deliveryFeignClient;

    /**
     * 过滤物流不同的商品
     *
     * @param dbShopCartItems 用户选择的商品项
     * @return 返回过滤掉的商品项item
     */
    public List<ShopCartItemVO> filterShopItemsByType(ShopCartOrderMergerVO shopCartOrderMerger, List<ShopCartItemVO> dbShopCartItems) {
        Map<Long, Integer> dvyTypeMap = shopCartOrderMerger.getDvyTypes().stream().collect(Collectors.toMap(DvyTypeDTO::getShopId, DvyTypeDTO::getDvyType));
        List<ShopCartItemVO> cartItems = new ArrayList<>();
        List<ShopCartItemVO> filterItems = new ArrayList<>();
        // 不可配送的套餐id
        Set<Long> comboIdList = new HashSet<>();
        for (ShopCartItemVO shopCartItem : dbShopCartItems) {
            Integer dvyType = dvyTypeMap.get(shopCartItem.getShopId());
            if (dvyType == 3 || Objects.equals(shopCartItem.getSpuMold(), 1)) {
                shopCartItem.setPlatformShareReduce(0L);
                cartItems.add(shopCartItem);
                LOGGER.info("无需配送的商品，shopCartItem:{}", shopCartItem);
                continue;
            }
            DeliveryModeBO deliveryModeVO = shopCartItem.getDeliveryModeBO();
            boolean hasShopDelivery = deliveryModeVO.getHasShopDelivery() != null && Objects.equals(dvyType, DeliveryType.DELIVERY.value()) && deliveryModeVO.getHasShopDelivery();
            boolean hasCityDelivery = deliveryModeVO.getHasUserPickUp() != null && Objects.equals(dvyType, DeliveryType.STATION.value()) && deliveryModeVO.getHasUserPickUp();
            boolean hasUserPickUp = deliveryModeVO.getHasCityDelivery() != null && Objects.equals(dvyType, DeliveryType.SAME_CITY.value()) && deliveryModeVO.getHasCityDelivery();
            if (hasShopDelivery || hasUserPickUp || hasCityDelivery) {
                LOGGER.info("有配送方式的商品，shopCartItem:{}", shopCartItem);
                // 设置平台分摊金额，为计算完商家之后计算平台优惠做准备
                shopCartItem.setPlatformShareReduce(0L);
                //是否只有一个商品或者只有一个套餐主商品  同时配送方式为同城配送, 不限制用户的地址是否满足配送，避免前端页面显示错误，结算订单的时候会再次判断是否满足配送
                // 过滤出实物商品
                int realItemSize = dbShopCartItems.stream().filter(item -> !Objects.equals(item.getSpuMold(), SpuMold.VIRTUAL.value()) && Objects.equals(item.getSpuType(), SpuType.NORMAL.value())).collect(Collectors.groupingBy(ShopCartItemVO::getSpuId)).size();
                boolean isOneAndSameCity = (dbShopCartItems.size() == 1 || realItemSize == 1) && Objects.equals(dvyType, DeliveryType.SAME_CITY.value());
                //过滤掉非自提且不在配送范围内的商品,或选择自提但不支持自提的商品
                boolean shouldFilter = (((!shopCartItem.getIsDelivery() && !hasCityDelivery) || (dvyType == 2 && !hasCityDelivery)) && !isOneAndSameCity);
                if (shouldFilter) {
                    filterItems.add(shopCartItem);
                    LOGGER.info("过滤掉非自提且不在配送范围内的商品,或选择自提但不支持自提的商品,shopCartItem:{}", shopCartItem);
                    // 不可配送的商品是套餐商品
                    if (Objects.nonNull(shopCartItem.getComboId())){
                        comboIdList.add(shopCartItem.getComboId());
                        LOGGER.info("过滤的商品是套餐商品,shopCartItem:{}", shopCartItem);
                    }
                } else {
                    cartItems.add(shopCartItem);
                    LOGGER.info("不过滤的商品项,shopCartItem:{}", shopCartItem);
                }
            } else {
                LOGGER.info("不可配送的商品,shopCartItem:{}", shopCartItem);
                filterItems.add(shopCartItem);
                // 不可配送的商品是套餐商品
                if (Objects.nonNull(shopCartItem.getComboId())){
                    LOGGER.info("不可配送的商品是套餐商品,shopCartItem:{}", shopCartItem);
                    comboIdList.add(shopCartItem.getComboId());
                }
            }
        }
        // 套餐中有一个不可配送，整个套餐都不可配送
        Iterator<ShopCartItemVO> shopCartItemVOIterator = cartItems.iterator();
        while (shopCartItemVOIterator.hasNext()){
            ShopCartItemVO cartItem = shopCartItemVOIterator.next();
            if (Objects.nonNull(cartItem.getComboId()) && comboIdList.contains(cartItem.getComboId())){
                filterItems.add(cartItem);
                shopCartItemVOIterator.remove();
            }
        }
        LOGGER.info("过滤掉的商品项:{}", filterItems);
        shopCartOrderMerger.setFilterShopItems(filterItems);
        return cartItems;
    }

    /**
     * 当算完一遍店铺的各种满减活动时，重算一遍订单金额
     */
    public void recalculateAmountWhenFinishingCalculateShop(ShopCartOrderMergerVO shopCartOrderMerger, List<ShopCartVO> shopCarts, UserDeliveryInfoVO userDeliveryInfo) {

        Map<Long, ShopTransFeeVO> shopIdWithShopTransFee = userDeliveryInfo.getShopIdWithShopTransFee();
        Map<Long, ShopTransFeeVO> supplierIdWithShopTransFeeMap = userDeliveryInfo.getSupplierIdWithShopTransFeeMap();
        shopCartOrderMerger.setSupplierIdWithShopTransFeeMap(userDeliveryInfo.getSupplierIdWithShopTransFeeMap());
        shopCartOrderMerger.setPreSaleTransFeeMap(userDeliveryInfo.getPreSaleTransFeeMap());
        if (Objects.isNull(supplierIdWithShopTransFeeMap)) {
            supplierIdWithShopTransFeeMap = new HashMap<>();
        }
        // 所有店铺的订单信息
        List<ShopCartOrderVO> shopCartOrders = new ArrayList<>();

        long actualTotal = 0;
        long total = 0;
        int totalCount = 0;
        long allOrderReduce = 0;
        long totalTransfee = 0;
        long scoreTotal = 0L;
        Map<Long, Integer> shopCityStatusMap = new HashMap<>();
        if (Objects.nonNull(userDeliveryInfo.getShopCityStatusVOS())) {
            shopCityStatusMap = userDeliveryInfo.getShopCityStatusVOS().stream().collect(Collectors.toMap(ShopCityStatusVO::getShopId, ShopCityStatusVO::getShopCityStatus));
        }
        Map<Long, Long> shopStartDeliveryFees = new HashMap<>();
        if (Objects.nonNull(userDeliveryInfo.getShopStartDeliveryFees())) {
            shopStartDeliveryFees = userDeliveryInfo.getShopStartDeliveryFees();
        }
        // 所有店铺所有的商品item
        for (ShopCartVO shopCart : shopCarts) {
            // 每个店铺的订单信息
            ShopCartOrderVO shopCartOrder = new ShopCartOrderVO();
            shopCartOrder.setShopCityStatus(shopCityStatusMap.containsKey(shopCart.getShopId()) ? shopCityStatusMap.get(shopCart.getShopId()) : null);
            shopCartOrder.setOrderType(shopCartOrderMerger.getOrderType().value());
            shopCartOrder.setShopId(shopCart.getShopId());
            shopCartOrder.setShopName(shopCart.getShopName());
            shopCartOrder.setShopType(shopCart.getShopType());
            shopCartOrder.setShopReduce(shopCart.getShopReduce());
            shopCartOrder.setStartDeliveryFee(shopStartDeliveryFees.containsKey(shopCart.getShopId()) ? shopStartDeliveryFees.get(shopCart.getShopId()).doubleValue() : 0L);            shopCartOrder.setTransfee(0L);
            shopCartOrder.setFreeTransfee(0L);
            shopCartOrder.setActualTotal(shopCart.getActualTotal());
            total += shopCart.getTotal();
            totalCount += shopCart.getTotalCount();
            allOrderReduce += shopCart.getShopReduce();

            // 积分订单使用积分
            if (Objects.equals(shopCartOrderMerger.getOrderType(), OrderType.SCORE)) {
                shopCartOrder.setUseScore(shopCart.getScoreTotal());
            }

            // 如果某家店因为各种优惠活动满减，使得金额变为负数，则这家店最低应该支付一分钱，而里面最贵的那件商品，也是支付一分钱，优惠金额 = （商品金额 - 一分钱）
            // 平台端的订单不使用优惠，不需要此判断
            if (shopCart.getActualTotal() < 1L && !Objects.equals(shopCart.getShopId(), Constant.PLATFORM_SHOP_ID)) {
                shopCartOrder.setActualTotal(1L);
                shopCartOrder.setShopReduce(shopCart.getTotal() - 1L);

                List<ShopCartItemVO> shopCartShopCartItem = getShopShopCartItem(shopCart.getShopCartItemDiscounts());
                resetActualTotal(shopCartShopCartItem);
            }

            //店铺优惠金额 = 优惠金额
            shopCartOrder.setShopReduce(shopCartOrder.getShopReduce());

            Set<Long> supplierIds = new HashSet<>();
            // 计算当前店铺的供应商发货商品运费
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCart.getShopCartItemDiscounts()) {
                Set<Long> ids = shopCartItemDiscount.getShopCartItems().stream().filter(shopCartItemVO -> Objects.equals(shopCartItemVO.getSupplierDeliveryType(), SupplierDeliveryType.SUPPLIER_DELIVERY.value()))
                        .map(ShopCartItemVO::getSupplierId).collect(Collectors.toSet());
                supplierIds.addAll(ids);
            }
            for (Long supplierId : supplierIds) {
                if (!supplierIdWithShopTransFeeMap.containsKey(supplierId)) {
                    continue;
                }
                ShopTransFeeVO supplierTransFeeVO = supplierIdWithShopTransFeeMap.get(supplierId);
                shopCartOrder.setActualTotal(shopCartOrder.getActualTotal() + supplierTransFeeVO.getTransfee());
                // 运费
                shopCartOrder.setTransfee(shopCartOrder.getTransfee() + supplierTransFeeVO.getTransfee());
                shopCartOrder.setFreeTransfee(shopCartOrder.getFreeTransfee() + supplierTransFeeVO.getFreeTransfee());
                totalTransfee += supplierTransFeeVO.getTransfee();
            }

            // 计算店铺运费
            if (CollectionUtil.isNotEmpty(shopIdWithShopTransFee) && shopIdWithShopTransFee.containsKey(shopCartOrder.getShopId())) {
                ShopTransFeeVO shopTransFeeVO = shopIdWithShopTransFee.get(shopCartOrder.getShopId());

                // 店铺的实付 = 购物车实付 + 运费
                shopCartOrder.setActualTotal(shopCartOrder.getActualTotal() + shopTransFeeVO.getTransfee());
                // 运费
                shopCartOrder.setTransfee(shopCartOrder.getTransfee() + shopTransFeeVO.getTransfee());
                shopCartOrder.setFreeTransfee(shopCartOrder.getFreeTransfee() + shopTransFeeVO.getFreeTransfee());
                totalTransfee += shopTransFeeVO.getTransfee();
            }
//            else {
//                // 运费
//                shopCartOrder.setTransfee(0L);
//                shopCartOrder.setFreeTransfee(0L);
//                // 店铺的实付 = 购物车实付 + 运费
//                shopCartOrder.setActualTotal(shopCartOrder.getActualTotal() + shopCartOrder.getTransfee());
//            }


            // 店铺优惠券优惠金额
            shopCartOrder.setCouponReduce(shopCart.getCouponReduce());
            shopCartOrder.setShopCartItemDiscounts(shopCart.getShopCartItemDiscounts());
            shopCartOrder.setCoupons(shopCart.getCoupons());
            shopCartOrder.setTotal(shopCart.getTotal());
            shopCartOrder.setTotalCount(shopCart.getTotalCount());
            shopCartOrder.setShopComboAmount(shopCart.getShopComboAmount());
            actualTotal += shopCartOrder.getActualTotal();
            if (Objects.equals(shopCartOrderMerger.getOrderType(), OrderType.SCORE)) {
                LOGGER.info("积分订单使用积分:{}", shopCart.getScoreTotal());
                shopCartOrder.setUseScore(shopCart.getScoreTotal());
            } else {
                shopCartOrder.setUseScore(shopCartOrder.getUseScore());
                LOGGER.info("非积分订单使用积分:{}", shopCartOrder.getUseScore());
            }
            shopCartOrder.setDiscountReduce(shopCart.getDiscountReduce());
            shopCartOrders.add(shopCartOrder);
            scoreTotal += shopCart.getScoreTotal();
        }

        shopCartOrderMerger.setActualTotal(actualTotal);
        shopCartOrderMerger.setTotal(total);
        shopCartOrderMerger.setTotalCount(totalCount);
        shopCartOrderMerger.setOrderReduce(allOrderReduce);
        shopCartOrderMerger.setTotalTransfee(totalTransfee);
        shopCartOrderMerger.setShopCartOrders(shopCartOrders);
        shopCartOrderMerger.setUserAddr(userDeliveryInfo.getUserAddr());
        shopCartOrderMerger.setShopCityStatus(userDeliveryInfo.getShopCityStatus());
        if (Objects.equals(shopCartOrderMerger.getOrderType(), OrderType.SCORE)) {
            shopCartOrderMerger.setUsableScore(scoreTotal);
        }
    }

    /**
     * 结束平台优惠的计算之后，还要重算一遍金额
     */
    public void recalculateAmountWhenFinishingCalculatePlatform(ShopCartOrderMergerVO shopCartOrderMerger, UserDeliveryInfoVO userDeliveryInfo) {
        Map<Long, ShopTransFeeVO> shopIdWithShopTransFee = userDeliveryInfo.getShopIdWithShopTransFee();
        //所有订单实际金额
        long actualTotal = 0L;
        //所有订单优惠金额
        long allOrderReduce = 0L;
        // 总运费金额
        long totalTransfee = 0L;
        // 运费减免金额
        long freeTransfee = 0L;

        List<ShopCartOrderVO> shopCartOrders = shopCartOrderMerger.getShopCartOrders();
        List<VirtualRemarkVO> virtualRemarkList = new ArrayList<>();
        for (ShopCartOrderVO shopCartOrder : shopCartOrders) {

            //订单实际金额
            long orderActualTotal = 0L;
            //商家优惠金额
            long orderReduceAmount = 0L;
            //商家优惠金额
            long orderPlatformAmount = 0L;

            List<ShopCartItemVO> shopCartShopCartItem = getShopShopCartItem(shopCartOrder.getShopCartItemDiscounts());

            for (ShopCartItemVO shopCartItem : shopCartShopCartItem) {
                shopCartItem.setShareReduce(shopCartItem.getShareReduce() + shopCartItem.getPlatformShareReduce());
                if (Objects.nonNull(shopCartItem.getComboId())) {
                    //套餐商品需要减去套餐优惠
                    shopCartItem.setActualTotal(shopCartItem.getTotalAmount() - shopCartItem.getShareReduce() - shopCartItem.getComboAmount());
                } else {
                    shopCartItem.setActualTotal(shopCartItem.getTotalAmount() - shopCartItem.getShareReduce());
                }

                orderActualTotal += shopCartItem.getActualTotal();
                orderReduceAmount += shopCartItem.getShareReduce();
                orderPlatformAmount += shopCartItem.getPlatformShareReduce();
                if (StrUtil.isNotBlank(shopCartItem.getVirtualRemark())) {
                    List<VirtualRemarkVO> virtualRemarks = JSON.parseArray(shopCartItem.getVirtualRemark(), VirtualRemarkVO.class);
                    virtualRemarks.forEach(virtualRemark -> virtualRemark.setSpuId(shopCartItem.getSpuId()));
                    shopCartItem.setVirtualRemarkList(virtualRemarks);
                    virtualRemarkList.addAll(shopCartItem.getVirtualRemarkList());
                }
            }
            // 如果是定金预售，优惠处理下定金和尾款
            if (Objects.equals(shopCartOrderMerger.getPreSaleType(), PreSaleType.DEPOSIT.value())) {
                // 定金预售只能买一个商品，直接处理这个商品
                ShopCartItemVO shopCartItemVO = shopCartShopCartItem.get(0);
                // 实际定金
                if (shopCartItemVO.getShareReduce() > shopCartItemVO.getBalanceAmount()) {
                    long actualDepositAmount = shopCartItemVO.getShareReduce() - shopCartItemVO.getBalanceAmount();
                    shopCartItemVO.setActualDepositAmount(Math.max(shopCartItemVO.getActualDepositAmount() - actualDepositAmount, 1L));
                }
                // 实际尾款 = max(尾款 - 优惠，0）
                shopCartItemVO.setActualBalanceAmount(Math.max(shopCartItemVO.getBalanceAmount() - shopCartItemVO.getShareReduce(), 0L));
                shopCartOrder.setShopReduce(shopCartOrder.getShopReduce() + shopCartItemVO.getDepositReduceAmount());
                shopCartOrderMerger.setTotalDepositReduceAmount(shopCartItemVO.getDepositReduceAmount());
                shopCartOrderMerger.setBalanceAmount(shopCartItemVO.getBalanceAmount());
                shopCartOrderMerger.setActualBalanceAmount(shopCartItemVO.getActualBalanceAmount());
                shopCartOrderMerger.setTotalDepositAmount(shopCartItemVO.getActualDepositAmount());
            }
            // 如果是折扣特别小的情况下，导致实际金额为0是，改变最小支付金额为0.01元,并且优惠金额减去0.01（积分抵扣除外，积分能够完全抵扣）
            // 此时的实际支付金额已经包含运费了
            boolean isMinPrice = shopCartOrder.getActualTotal() < 1
                    && (shopCartOrder.getScoreReduce() == null || shopCartOrder.getScoreReduce() < 1L);
            if(isMinPrice) {
                // 重算订单项
                resetActualTotal(shopCartShopCartItem);
                shopCartOrder.setActualTotal(1L);
                shopCartOrder.setShopReduce(shopCartOrder.getTotal() - 1L);
            }
            if (shopCartOrder.getLevelFreeTransfee() != null && shopCartOrder.getLevelFreeTransfee() != 0L) {

                // 店铺先说包邮，然后平台再说会员包邮，所以实际上平台的包邮剩下来的邮费 = shopCartOrder.getLevelFreeTransfee() - shopCartOrder.getTransfee()

                Long transfee = shopCartOrder.getLevelFreeTransfee() - shopCartOrder.getTransfee();
                //放入平台优惠金额,如果用户等级免自营店运费也要放进去
                shopCartOrder.setPlatformAmount(shopCartOrder.getPlatformAmount() + transfee);
                shopCartOrder.setActualTotal(orderActualTotal - transfee);
                // 平台会员减免运费金额
                freeTransfee += shopCartOrder.getLevelFreeTransfee();
            }


            actualTotal += shopCartOrder.getActualTotal();
            allOrderReduce += shopCartOrder.getShopReduce();
            totalTransfee += shopCartOrder.getTransfee();
            // 店铺减免运费金额
            freeTransfee += (Objects.isNull(shopCartOrder.getLevelFreeTransfee()) ? 0 : shopCartOrder.getFreeTransfee());
        }
        shopCartOrderMerger.setActualTotal(actualTotal);
        shopCartOrderMerger.setVirtualRemarkList(virtualRemarkList);
        shopCartOrderMerger.setTotalTransfee(totalTransfee);
        shopCartOrderMerger.setFreeTransfee(freeTransfee);
        shopCartOrderMerger.setOrderReduce(allOrderReduce);
        shopCartOrderMerger.setUserAddr(userDeliveryInfo.getUserAddr());
        shopCartOrderMerger.setShopCityStatus(userDeliveryInfo.getShopCityStatus());
    }


    /**
     * 重新计算金额，避免订单无法支付
     */
    private void resetActualTotal(List<ShopCartItemVO> shopCartShopCartItem) {
        Iterator<ShopCartItemVO> iterator = shopCartShopCartItem.iterator();
        while (iterator.hasNext()) {
            ShopCartItemVO shopCartItem = iterator.next();
            shopCartItem.setShareReduce(shopCartItem.getShareReduce() + shopCartItem.getPlatformShareReduce());
            shopCartItem.setActualTotal(shopCartItem.getTotalAmount() - shopCartItem.getShareReduce());
            if (iterator.hasNext()) {
                shopCartItem.setActualTotal(0L);
                shopCartItem.setShareReduce(shopCartItem.getTotalAmount());
            } else {
                shopCartItem.setActualTotal(1L);
                shopCartItem.setShareReduce(shopCartItem.getTotalAmount() - 1L);
            }
        }
    }

    /**
     * 获取店铺下的所有订单
     */
    private List<ShopCartItemVO> getShopShopCartItem(List<ShopCartItemDiscountVO> shopCartItemDiscounts) {
        List<ShopCartItemVO> shopCartShopCartItem = new ArrayList<>();
        for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartItemDiscounts) {
            shopCartShopCartItem.addAll(shopCartItemDiscount.getShopCartItems());
        }
        shopCartShopCartItem.sort(Comparator.comparingDouble(ShopCartItemVO::getTotalAmount));
        return shopCartShopCartItem;
    }


    /**
     * 确认订单计算平台佣金
     *
     * @param shopCartOrderMerger
     */
    public void confirmPlatformCommission(ShopCartOrderMergerVO shopCartOrderMerger) {
        for (ShopCartOrderVO shopCartOrder : shopCartOrderMerger.getShopCartOrders()) {
            Long totalPlatformCommission = 0L;
            for (ShopCartItemDiscountVO shopCartItemDiscount : shopCartOrder.getShopCartItemDiscounts()) {
                for (ShopCartItemVO shopCartItem : shopCartItemDiscount.getShopCartItems()) {
                    if (Objects.equals(shopCartOrderMerger.getOrderType().value(), OrderType.SCORE.value())) {
                        // 分摊比例
                        shopCartItem.setRate(0.0);
                        // 平台佣金
                        shopCartItem.setPlatformCommission(0L);
                        shopCartItem.setSupplierRate(0.0);
                        shopCartItem.setPurchasePlatformCommission(0L);
                        continue;
                    }
                    // 平台佣金,如果是商家代销，供应商采购价的佣金也需要计算
                    // 平台对商家的差价抽佣 = （商家定的销售价格 - 供应商价格）-（商家定的销售价格 - 供应商价格）* 平台抽佣百分比
                    // 平台对商家的差价抽佣 = （用户实付金额 + 平台优惠金额 - 供应商金额） * 比例
                    long shopAmount = shopCartItem.getActualTotal() + shopCartItem.getPlatformShareReduce() - shopCartItem.getTotalPurchaseAmount();
                    shopAmount = Math.max(shopAmount, 0L);
                    // 平台佣金
                    shopCartItem.setPlatformCommission(PriceUtil.divideByBankerRounding((long) ((shopAmount) * shopCartItem.getRate()), 100));
                    // 供应商没有平台优惠，此时不用加上平台优惠进行计算
                    // 平台对供应商的抽佣 = 供应商采购价 * 平台抽佣百分比
                    shopCartItem.setPurchasePlatformCommission(PriceUtil.divideByBankerRounding((long) (shopCartItem.getTotalPurchaseAmount() * shopCartItem.getSupplierRate()), 100));
                    totalPlatformCommission += shopCartItem.getPlatformCommission();
                }
            }
            shopCartOrder.setPlatformCommission(totalPlatformCommission);
        }
    }


    public void cacheCalculatedInfo(Long userId, ShopCartOrderMergerVO shopCartOrderMerger) {
        // 防止重复提交
        RedisUtil.STRING_REDIS_TEMPLATE.opsForValue().set(OrderCacheNames.ORDER_CONFIRM_UUID_KEY + CacheNames.UNION + userId, String.valueOf(userId));
        // 保存订单计算结果缓存，省得重新计算 并且 用户确认的订单金额与提交的一致
        cacheManagerUtil.putCache(OrderCacheNames.ORDER_CONFIRM_KEY, String.valueOf(userId), shopCartOrderMerger);
    }

    public void checkAddr(List<ShopCartItemVO> shopCartItemsDb, Long userId, Long addrId) {
        for (ShopCartItemVO shopCartItemVO : shopCartItemsDb) {
            //判断用户的默认地址是否在配送范围内
            if(Objects.equals(shopCartItemVO.getSpuType(), SpuType.ACTIVE.value()) || Objects.equals(shopCartItemVO.getSpuMold(), 1) || Objects.equals(userId, null)){
                shopCartItemVO.setIsDelivery(true);
                LOGGER.info("活动商品或虚拟商品不校验地址");
            }else {
                shopCartItemVO.setIsDelivery(deliveryFeignClient.checkAddr(shopCartItemVO.getDeliveryTemplateId(), userId, addrId).getData());
                LOGGER.info("校验地址结果：{}", shopCartItemVO.getIsDelivery());
            }
        }
    }

}
